package utils

import (
	"regexp"
	"strconv"
)

var numbReg *regexp.Regexp

func init() {
	numbReg, _ = regexp.Compile("[-]?[1-9]\\d*[\\.]?\\d*|[-]?0[\\.]?\\d*[1-9]\\d*$")
}

func GetNumb(str string) (num float64, ok bool) {
	numbStr := numbReg.FindString(str)
	if len(numbStr) == 0 {
		return
	}

	num, err := strconv.ParseFloat(numbStr, 64)
	if err != nil {
		return
	}

	ok = true
	return
}

func GetNumbStr(str string) (numbStr string) {
	numbStr = numbReg.FindString(str)
	return
}

func TrimLastZero(str string) string {
	index := len(str)
	for i := len(str) - 1; i >= 0; i-- {
		if str[i] == '0' {
			index = i
		} else if str[i] == '.' {
			index = i
			break
		} else {
			break
		}
	}

	if index == 0 {
		return str
	}
	return str[0:index]
}

func Float2Int(f float64) int {
	return int(f + 0.5)
}
